import getUserTempId from "@/utils/userTempId"
//登录请求
import {requestLogin,requestUserInfo,requestLogout} from "@/api"

const state ={
   userTempId:getUserTempId(),
   token:localStorage.getItem('user_token')||'',
   nickName:''
}
const mutations ={
    SET_TOKEN_STATE(state,payload){
        state.token = payload
    },
    SET_USERINFO_STATE(state,nickName){
            state.nickName = nickName
    },
    SET_LOGOUT_STATE(state){
        //退出登录后清掉token，nickname，和本地存储的token
        state.token = ''
        state.nickName = ''
        localStorage.removeItem('user_token')
    }
}
const actions ={
    //获取token
    async getToken({commit},userInfo){
        //登录请求拿到的是result是一个对象，对象中的token是需要保存在vuex的东西
        const result = await requestLogin(userInfo)
        // console.log(result)
        commit("SET_TOKEN_STATE",result.token)
        //请求到token之后，需要进行持久化到本地，否则刷新后就又要重新登录
        localStorage.setItem("user_token",result.token)
    },
    //获取用户登录的信息
    async getUserInfo({commit}){
        const result = await requestUserInfo()
        // console.log(result,'1111')

        commit("SET_USERINFO_STATE",result.nickName)
    },
    //退出登录
    async getlogout({commit}){
        await requestLogout()
        commit('SET_LOGOUT_STATE')
    }
}
const getters={

}

export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters

}